package com.idanchuang.count.controller

import com.idanchuang.count.config.IntegrationTestConfig
import com.idanchuang.count.service.AsyncCountCommandHandler
import com.idanchuang.count.service.impl.AsyncCountCommandHandlerImpl
import com.idanchuang.count.support.UserCountChecker
import com.idanchuang.user.count.service.api.request.command.count.SceneCountIncrement
import com.idanchuang.user.count.service.api.request.command.count.UserMultiScenesCountUpdateCommand
import com.idanchuang.user.count.service.api.request.query.count.UserCountBatchQuery
import org.spockframework.spring.SpringBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.test.context.ContextConfiguration
import org.testcontainers.spock.Testcontainers
import spock.lang.Specification

/**
 *
 * @author Richard_yyf
 * @version 1.0 2021/6/7
 */
@ContextConfiguration(
        initializers = IntegrationTestConfig.IntegrationTestInitializer.class,
        classes = [IntegrationTestConfig.class])
@Testcontainers
class ControllerAspectTest extends Specification {

    @SpringBean
    AsyncCountCommandHandler asyncCountCommandHandler = Mock(AsyncCountCommandHandlerImpl)

    static def bizCode = "bizA"

    @Autowired
    private StringRedisTemplate stringRedisTemplate

    @Autowired
    private UserCountServiceController userCountServiceController

    @Autowired
    private UserCountChecker countChecker

    def cleanup() {
        // runs after every feature method
        // clean
        Set<String> keys = stringRedisTemplate.keys("cs:*")
        keys.addAll(stringRedisTemplate.keys("csr:*"))
        println("delete keys: " + keys.toString())
        stringRedisTemplate.delete(keys)
    }

    def "test_uid_check_enable"() {
        def userCode = 100
        def scene1 = "sceneA"
        def scene2 = "sceneB"

        def command1 = new UserMultiScenesCountUpdateCommand(
                bizCode : bizCode,
                userCode : userCode,
                sceneCountIncrements : [
                        new SceneCountIncrement(scene: scene1, incrementAmount: 5),
                        new SceneCountIncrement(scene: scene1, incrementAmount: 5)
                ]
        )


        when:
        userCountServiceController.multiCount(command1)
        def queryRet = userCountServiceController.batchQuery(new UserCountBatchQuery(
                userCode: userCode,
                sceneList: [scene1],
                bizCode: bizCode
        ))

        then:
        queryRet != null
        queryRet.data.userCode == userCode
        queryRet.data.scenesCountMap.get(scene1) == 10

        countChecker.checkUidExist(command1.uid, command1.getBizCode())
    }
}
